/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManMantenimiento.java
 *
 * Created on 12/02/2011, 07:17:57 PM
 */

package com.catosist.run.application.vehiculo.mantenimiento;

import com.catosist.run.application.Util.MiModelo;
import com.catosist.run.business.gestorMantenimiento.GestorMantenimiento;
import com.catosist.run.business.gestorvehiculo.GestorVehiculo;
import com.catosist.run.services.MantenimientoDTO;
import com.catosist.run.services.VehiculoDTO;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author igorov
 */
public class ManMantenimiento extends javax.swing.JFrame {

    /** Creates new form ManMantenimiento */
    public ManMantenimiento() {
        initComponents();
    }

    public ManMantenimiento(int vehiculoId, GestorVehiculo gestorVehiculo) {
       initComponents();
       this.vehiculoId = vehiculoId;
       this.gestorVehiculo = gestorVehiculo;
       iniciar();
       refresh();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        lblTitle = new javax.swing.JLabel();
        btnAgregar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        lblTotal = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        lblTitle.setFont(new java.awt.Font("Dialog", 0, 18));
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(ManMantenimiento.class);
        lblTitle.setText(resourceMap.getString("lblTitle.text")); // NOI18N
        lblTitle.setName("lblTitle"); // NOI18N

        btnAgregar.setText(resourceMap.getString("btnAgregar.text")); // NOI18N
        btnAgregar.setName("btnAgregar"); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEditar.setText(resourceMap.getString("btnEditar.text")); // NOI18N
        btnEditar.setName("btnEditar"); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        lblTotal.setFont(resourceMap.getFont("lblTotal.font")); // NOI18N
        lblTotal.setText(resourceMap.getString("lblTotal.text")); // NOI18N
        lblTotal.setName("lblTotal"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
                            .addComponent(lblTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnAgregar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnEditar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(lblTotal)
                        .addGap(160, 160, 160))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addComponent(lblTotal)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        DialogMantenimiento dialogMantenimiento = new DialogMantenimiento(this, true, vehiculoId, 0);
        dialogMantenimiento.setLocationRelativeTo(this);
        dialogMantenimiento.setVisible(true);
        refresh();

    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        // TODO add your handling code here:
        try{
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            if (i == 0) {
                throw new Exception();
            }
            DialogMantenimiento dialogMantenimiento = new DialogMantenimiento(this, true, vehiculoId, i);
            dialogMantenimiento.setLocationRelativeTo(this);
            dialogMantenimiento.setVisible(true);
            refresh();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }

    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());

       int result = JOptionPane.showConfirmDialog(this, "Realmente desea eliminar el registro?", "Eliminar Gasto", JOptionPane.YES_NO_OPTION);
       if (result == JOptionPane.YES_OPTION) {
           gestorMantenimiento.deleteById(i);
           refresh();
       }
    }//GEN-LAST:event_btnEliminarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManMantenimiento().setVisible(true);
            }
        });
    }
    private void iniciar() {
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorMantenimiento = (GestorMantenimiento) ctx.getBean("gestorMantenimiento");
        
    }

    public JPanel getPanel(){
        return jPanel1;
    }
    private void refresh() {

        try{
            
        VehiculoDTO vehiculoDTO = gestorVehiculo.getById(vehiculoId);
        List<MantenimientoDTO> mantenimientoDTOs = gestorMantenimiento.getMantenimientosById(vehiculoId);
        //List<MantenimientoDTO> mantenimientoDTOs = gestorMantenimiento.getAll();

        this.lblTitle.setText("Mantenimientos del vehiculo:      " 
                + "             Placa: " + vehiculoDTO.getPlaca()
                + "             Marca: " + vehiculoDTO.getMarca());

        DefaultTableModel model = new MiModelo();
        model.addColumn("id");
        model.addColumn("Fecha");
        model.addColumn("Cantidad");
        model.addColumn("Unidad de medida");
        model.addColumn("Descripcion");
        model.addColumn("Detalle");
        model.addColumn("Precio Unitario");
        model.addColumn("Monto");
        

        float total = 0f;
        //List<MantenimientoDTO> mantenimientoDTOs = gestorMantenimiento.getMantenimientosById(vehiculoId);
        for (Iterator<MantenimientoDTO> it = mantenimientoDTOs.iterator(); it.hasNext();) {
            MantenimientoDTO mantenimientoDTO = it.next();
            model.addRow(mantenimientoDTO.toArray());
            total += mantenimientoDTO.getTotal();
        }
        this.jTable1.setModel(model);
        this.lblTotal.setText("Total: " +String.valueOf(total));
        } catch (Exception e) {
          System.out.println("Errorrrr" + e.getMessage());  
        }
        

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblTotal;
    // End of variables declaration//GEN-END:variables
    private GestorMantenimiento gestorMantenimiento;
    private GestorVehiculo gestorVehiculo;
    private int vehiculoId;
    ApplicationContext ctx;
}
